package com.mobile.util.jackson;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.CustomSerializerFactory;

public class CustomJacksonObjectMapper extends ObjectMapper {
	
	private final String mask = "yyyy-MM-dd'T'HH:mm:ss.SSS";
	
	@PostConstruct 
	public void afterProps(){
		configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
		configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
		
		CustomSerializerFactory factory = new CustomSerializerFactory();
		factory.addSpecificMapping(Date.class, new JsonSerializer<Date>() {

			@Override
			public Class<Date> handledType() { return Date.class; }

			@Override
			public void serialize(Date value, JsonGenerator jgen,
					SerializerProvider provider) throws IOException,
					JsonProcessingException {
				
				SimpleDateFormat df = new SimpleDateFormat(mask);
				String data = df.format(value);
				String timezone = new SimpleDateFormat("Z").format(value);
				//Incluindo caracter ':' no timezone para manter compatibilidade com o Javascript 
				timezone = StringUtils.left(timezone, 3) + ":" + StringUtils.right(timezone, 2); 
				jgen.writeString(data+timezone);
			}});
		
            this.setSerializerFactory(factory);
	}
	
}
